<template>
  <el-skeleton :loading="searchLoading" v-if="showSearch">
    <el-form
      :model="searchForm"
      ref="searchRef"
      @submit.prevent="handlerSearch"
      class="wd-search-form flex flex-col"
      v-if="searchColumns.length > 0"
    >
      <div class="flex">
        <el-row class="flex-1">
          <el-col
            v-for="(component, index) in searchColumns"
            :key="index"
            :span="6"
            class="mb-2"
          >
            <el-form-item :prop="component.dataIndex">
              <slot
                :name="`${component.dataIndex}`"
                v-bind="{ searchForm, component }"
              >
                <component
                  :is="
                    getComponentName(
                      component.searchFormType ?? component.formType
                    )
                  "
                  :component="component"
                />
              </slot>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="flex flex-col">
          <el-form-item class="!mb-2">
            <slot name="searchBeforeButtons" />
            <slot name="searchButtons">
              <el-button
                type="primary"
                native-type="submit"
                :loading="searchLoading"
              >
                <template #icon>
                  <icon icon="vi-tdesign:search"></icon>
                </template>
                {{ options.searchSubmitButtonText || "搜索" }}
              </el-button>
            </slot>
            <slot name="searchAfterButtons" />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSearch" :disabled="searchLoading">
              <template #icon>
                <icon icon="vi-ant-design:delete-outlined"></icon>
              </template>
              {{ options.searchResetButtonText || "重置" }}
            </el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
  </el-skeleton>
</template>

<script setup>
import { ref, inject, provide, markRaw } from "vue";
import { cloneDeep, isFunction } from "lodash";
import WdFormInput from "./searchFormItem/search-input.vue";
import WdFormSelect from "./searchFormItem/search-select.vue";
import WdFormPicker from "./searchFormItem/search-picker.vue";

const options = inject("options");
const columns = inject("columns");
const requestParams = inject("requestParams");

const searchLoading = ref(false);
const showSearch = ref(true);
const searchRef = ref(null);
const searchColumns = ref([]);
const searchForm = ref({});

provide("searchForm", searchForm);

const emit = defineEmits(["search"]);

const getSearchAllColumns = (cls = []) => {
  return cls.flatMap((item) => {
    if (item.children?.length > 0) {
      return getSearchAllColumns(item.children);
    }
    return item.dataIndex && item.search === true ? [item] : [];
  });
};

const initSearchColumns = () => {
  if (columns.value.length > 0) {
    searchColumns.value = cloneDeep(
      getSearchAllColumns(columns.value).filter(
        (item) =>
          item.search === true && options.tabs?.dataIndex !== item.dataIndex
      )
    );
  }
};

const handlerSearch = async () => {
  try {
    searchLoading.value = true;
    const isValid = await searchRef.value?.validate();

    if (isValid === false) return;

    const rawParams = { ...searchForm.value };
    const [start, end] = rawParams.reg_time || [];

    const params = {
      ...rawParams,
      ...(start && end
        ? { start_time: start, end_time: end }
        : { start_time: undefined, end_time: undefined }),
    };

    // 可选：剔除 undefined/null 的参数
    const cleanedParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v != null && v !== '')
    );

    emit("search", cleanedParams);
  } finally {
    searchLoading.value = false;
  }
};


const resetSearch = async () => {
  // 先重置表单
  searchRef.value?.resetFields();

  // 然后手动清空所有字段
  for (const key in searchForm.value) {
    searchForm.value[key] = undefined;
  }

  // 处理范围查询字段
  Object.keys(searchForm.value).forEach((item) => {
    const temp = item.match(/^(.+)Min$/);
    if (temp) {
      searchForm.value[temp[1] + "Min"] = undefined;
      searchForm.value[temp[1] + "Max"] = undefined;
    }
  });

  if (isFunction(options.resetSearch)) {
    await options.resetSearch(searchForm.value);
  }
  emit("search", searchForm.value);
};

const componentList = ref({
  WdFormSelect: markRaw(WdFormSelect),
  WdFormPicker: markRaw(WdFormPicker),
  WdFormInput: markRaw(WdFormInput),
});

const getComponentName = (formType) => {
  if (["select", "radio", "checkbox", "transfer"].includes(formType)) {
    return componentList.value["WdFormSelect"];
  } else if (
    ["date", "month", "year", "week", "quarter", "range", "time"].includes(
      formType
    )
  ) {
    return componentList.value["WdFormPicker"];
  } else {
    return componentList.value["WdFormInput"];
  }
};

initSearchColumns();

const setSearchHidden = () => (showSearch.value = false);
const setSearchDisplay = () => (showSearch.value = true);
const setSearchLoading = () => (searchLoading.value = true);
const setSearchUnLoading = () => (searchLoading.value = false);
const getSearchFormRef = () => searchRef.value;
const getSearchColumns = () => searchColumns.value;

defineExpose({
  initSearchColumns,
  getSearchFormRef: () => searchRef.value,
  getSearchColumns: () => searchColumns.value,
  showSearch,
  resetSearch,
  setSearchHidden: () => (showSearch.value = false),
  setSearchDisplay: () => (showSearch.value = true),
  setSearchLoading: () => (searchLoading.value = true),
  setSearchUnLoading: () => (searchLoading.value = false),
});
</script>

<style lang="less" scoped>
.wd-search-form {
  display: flex;
  padding-bottom: 1rem;
  border-bottom: 1px solid #f4f4f5;
  margin-bottom: 1rem;
  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    min-width: 150px;
    margin-right: 10px;
    //background-color: #f4f4f5;
    border-radius: 4px;
    box-shadow: 0 0 0 1px #dfdfdf inset;
    &.is-focus {
      box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
